var http = require("http");
var config = require("./config.js");
var request = require("request");
var express = require("express");
var cheerio = require("cheerio");
var async = require("async");
var fs = require("fs");

var app = express();

app.engine("html",require("express-art-template"));
app.use('/static/',express.static("./static/"));
// app.set("views","./page") //改变默认视图路径

app.get("/",function(req,res){
  res.render("index.html",{data:[]})
})

app.get("/getReptile",function(req,res){
  var query = req.query;
  console.log(query)
  var arr = [];
  var page = query.page?query.page:1;
  var limit = query.limit?query.limit:1;
  var path = query.path;
  async function asyncRequest(){
    do{
      switch(query.type){
        case "1":
          var result = await goRequest01(path,page);
          console.log("996result",result)
          arr = arr.concat(dealData01(result))
        break;
        case "2":

        break;
      }
      page++;
    }while(page<=limit)
    return arr;
  }
  asyncRequest().then(e=>{
    res.render('getReptile.html',{data:e})
    console.log(e)
  })
})

function goRequest01(path,page=1){
  return new Promise((resolve, reject) => {
    request(path+page,function(err,result){
      if(err){
        reject(err)
      }
      fs.writeFile("./code/demo.html",JSON.stringify(result),function(){})
      resolve(result)
    })
  });
}

function dealData01(re){
  var arr = [];
  var $ = cheerio.load(re.body);
  console.log("dealData0166",$(".list_pic .item"))
  $(".list_pic .item").each(function(i){
    var obj = {};
    obj.list_img = $(this).children(".goods-content").children(".goods-pic").children("a").children("img").attr("src")
    obj.title = $(this).children(".goods-content").children(".goods-info").children(".goods-name").children("a").text()
    obj.price = $(this).children(".goods-content").children(".goods-info").children(".goods-price").children(".sale-price").text().replace("¥","")
    obj.store = $(this).children(".goods-content").children(".goods-info").children(".store").children("a").text()
    obj.detail_img = []
    $(this).children(".goods-content").children(".goods-info").children(".goods-pic-scroll-show").children("ul").children("li").each(function(j){
      var detail_img_obj = {}
      var that = this;
      var a = $(that).children("a").children("img").attr("src").split("/")
      detail_img_obj.name = a[a.length-1]
      detail_img_obj.src = $(that).children("a").children("img").attr("src")
      obj.detail_img.push(detail_img_obj)
    })
    arr.push(obj);
  })
  return arr;
}

app.listen(6689,function(){
  console.log("gogogo")
})